package gatperdut.chato.core.messaging.replies;

import gatperdut.chato.core.ChatoServer;
import gatperdut.chato.core.messaging.grammar.messinfo.CreatePlayerInfo;
import gatperdut.chato.core.messaging.packagers.PlayersPackager.PlayerJSONAttr;
import gatperdut.chato.model.Chato.Player.Player;

public class CreatePlayerReply extends Reply {

    public CreatePlayerReply( CreatePlayerInfo createPlayerInfo, ChatoServer chatoServer ) {
        super( createPlayerInfo, chatoServer );
    }

    @Override
    public String send() {
        String username = (String) getMessageInfo().getPlayerData().get( PlayerJSONAttr.USERNAME.getName() );
        String password = (String) getMessageInfo().getPlayerData().get( PlayerJSONAttr.PASSWORD.getName() );
        if ( getChatoServer().getEntityHandler().isUsernameRegistered( username ) ) {
            return getPlayersPackager().packageRegistrationResult( null ).toJSONString();
        }
        else {
            Player player = getChatoServer().getEntityHandler().addPlayerAccount( username, password );
            return getPlayersPackager().packageRegistrationResult( player ).toJSONString();
        }
    }

    @Override
    public CreatePlayerInfo getMessageInfo() {
        return (CreatePlayerInfo) super.getMessageInfo();
    }

}
